package com.hmdp.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.myconst.KeyConst;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.hmdp.myconst.KeyConst.LOGIN_USER_CODE;
import static com.hmdp.myconst.KeyConst.LOGIN_USER_TOKEN;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.验证手机号码是否正确
        if(RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机号码格式是错误的");
        }
        //2.后台生成对应的验证码
        String code = RandomUtil.randomNumbers(6);

        //3.保存验证码
        // 3.1存储在redis中+保存时间
       String codeKey= LOGIN_USER_CODE +phone;
        stringRedisTemplate.opsForValue().set(codeKey,code,1, TimeUnit.MINUTES);

        //4.返回验证码
        log.debug("验证码是:{}",code);
        return Result.ok(code);
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        String phone = loginForm.getPhone();
        //1.校验手机号码有没有格式的错误
        if (RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机号有问题");
        }
        //2.从redis取出进行对比
        String cacheCode =stringRedisTemplate.opsForValue().get(LOGIN_USER_CODE+phone);
        String code = loginForm.getCode();

        if(StrUtil.isBlank(cacheCode)||!StrUtil.equals(cacheCode,code)){
            return Result.fail("验证码有误");
        }
        //3.查询账号是否存在
       User user= userMapper
               .selectOne(new LambdaQueryWrapper<User>().eq(User::getPhone,phone));
        if(user==null){
             user = new User();
             user.setPhone(phone);
            userMapper.insert(user);
        }

        //4.保存账号在redis中
        //4.1转化数据类型-->json
        String userStr = JSONUtil.toJsonStr(user);
        //5.生成对应的token
        String token = UUID.randomUUID().toString();
        //6.保存对应的token,使用token获取到对应的user
        stringRedisTemplate.opsForValue()
                .set(LOGIN_USER_TOKEN+token,userStr,10,TimeUnit.MINUTES);
        //7.返回token
        return Result.ok(token);
    }

    @Override
    public Result getMe() {
        User user = userMapper.selectById(UserHolder.getUser().getId());
        return Result.ok(user);
    }
}
